define(['lib','text!app/menu.tpl'], function(LIB,tpl) {
	Menu = Backbone.Model.extend({
		defaults:{
			id:"NULL",
			title:"TITLE",
			url:"",
			icon:"",
			submenu:[]
		}
	});
	MenuGroup = Backbone.Collection.extend({
		model:Menu,
		url:LIB.getConst().ROUTE.MENU_ACTION,
		initialize: function(models, options) {
			
		},
		parse : function(data) {
			var arrayObj = new Array(data.datas.length);
        	$.each(data.datas, function (i,item) {
        		var submenu = [];
        		if(LIB.isArray(item.submenu) && item.submenu.length > 0){
        			submenu = new Array(item.submenu.length);
					$.each(item.submenu, function (i,it) {
		        		var m = new Menu();		        		
		        		m.set({id:it.id,title:it.title,url:it.url,icon:it.icon,submenu:[]});
		        		submenu[i]=m;
		        	});
        		}
        		var menu = new Menu();
        		menu.set({id:item.id,title:item.title,url:item.url,icon:item.icon,submenu:submenu});
        		arrayObj[i]=menu;
        	});        	
        	return arrayObj;
		}
	});
	MenuView = Backbone.View.extend({
		el: $(".sidebar-menu"),
		template: _.template(tpl),
		initialize: function() {
			console.log("init menu list");
			this.menus = new MenuGroup(Menu, {view: this});
			_this = this;
			this.menus.fetch({success:function(collection, response){
				_this.render();
			}});
		},
		render: function() {
            datas = this.menus.toJSON();
            this.$el.html(this.template(datas));
      	},
		events: {
			//事件绑定，绑定Dom中id为check的元素
			"click .treeview > a":"menu",
			"click .treeview-menu > li": "submenu"
		},
		menu:function(event){
			var dom = $(event.target).parents('li');
			var sub=dom.children('.treeview-menu');
			if(sub.length > 0){				
				sub.toggle();
			} else {
				var t = dom.attr('title');
				var u = dom.attr('act');
				var i = dom.attr('icon');
				Backbone.trigger(LIB.getConst().MESSAGE.ADD_TAB_PAGE,{"title":t,"url":u,"icon":i});//发送打开tab消息；
			}
		},
		submenu:function(event){
			var dom = $(event.target).parents('li');
			var t = dom.attr('title');
			var u = dom.attr('act');
			var i = dom.attr('icon');
			Backbone.trigger(LIB.getConst().MESSAGE.ADD_TAB_PAGE,{"title":t,"url":u,"icon":i});//发送打开tab消息；
		}
	});	
});